package org.andy.platform.test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * 常见方法——计算密集型，设为CPU个数+1；IO密集型，设为2*CPU个数+1<br>
 * 精确计算——（ IO等待时间/CPU计算时间 + 1 ）* CPU个数<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/2/6 下午3:22
 */
public class Sum extends RecursiveTask<Long> {

    /**
     * {变量说明}
     */
    private static final Long THRESHOLD = 100L;
    private Long start;
    private Long end;

    public Sum(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long sum = 0L;
        if ((end - start) < THRESHOLD) {
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //            System.out.println("fork");
            Long middle = (start + end) / 2;
            Sum left = new Sum(start, middle);
            Sum right = new Sum(middle + 1, end);
            left.fork();
            right.fork();

            sum = left.join() + right.join();
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        Future<Long> result = pool.submit(new Sum(0L, 10000L));
        //        pool.shutdown();
        System.out.println(result.get());

    }

}
